<template>
  <div class="order-box">
    <el-row
      class="order-title"
      type="flex"
      justify="space-between"
      align="center"
    >
      <ul class="order-menu">
        <li class="active">订单管理</li>
      </ul>
      <el-form class="order-search" size="small">
        <el-row type="flex">
          <el-form-item style="width: 130px" prop="org">
            <el-select v-model="search.org" clearable @change="getOrder">
              <template #prefix>组织： </template>
              <el-option
                v-for="item in orgOption"
                :key="item.id"
                :label="item['key_value']"
                :value="item['key_value']"
              />
            </el-select>
          </el-form-item>
          <el-form-item style="width: 130px" prop="cj">
            <el-select v-model="search.cj" clearable @change="getOrder">
              <template #prefix>车间：</template>
              <el-option
                v-for="item in cjOption"
                :key="item.id"
                :label="item['key_value']"
                :value="item['key_value']"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="order-w" prop="pzcode" style="width: 150px">
            <el-select v-model="search.pz" clearable @change="getOrder">
              <template #prefix>品种名称：</template>
              <el-option
                v-for="item in pzOption"
                :key="item.id"
                :label="item['key_value']"
                :value="item['key_value']"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="order-w" prop="ddjq">
            <el-date-picker
              v-model="search.ddjq"
              value-format="yyyy-MM-dd"
              prefix-icon="order-time"
              placeholder="请选择订单交期"
              clearable
              @change="getOrder"
            />
          </el-form-item>
        </el-row>
      </el-form>
    </el-row>

    <div class="box-main">
      <el-row
        class="search-box"
        type="flex"
        justify="space-between"
        align="center"
      >
        <div style="width: 242px">
          <el-input
            size="small"
            v-model="search.ddbh"
            placeholder="搜索订单编号"
            clearable
            prefix-icon="el-icon-search"
            @blur="getOrder"
          />
        </div>
        <div>
          <el-button
            type="primary"
            icon="el-icon-circle-plus-outline"
            size="small"
            @click="insertOrder"
            >新增订单</el-button
          >
          <!-- <el-button size="small" @click="importShow()">导入订单</el-button>
          <el-button size="small">导出订单</el-button> -->
          <el-button size="small" @click="mergeShow('open')"
            >合并订单</el-button
          >
          <el-button
            size="small"
            type="primary"
            @click="delOrder('', 'multiple')"
            >删除订单</el-button
          >
        </div>
      </el-row>
      <div class="common-table order-table" ref="table" v-loading="loading">
        <el-table
          ref="orderTable"
          :data="data"
          :row-class-name="getRowClass"
          style="width: 100%"
          @expand-change="expandRow"
          :max-height="tableHeight"
        >
          <el-table-column type="selection" width="40" align="center" />
          <el-table-column type="expand" width="15" align="center" fixed="left">
            <template v-if="props.row.children" slot-scope="props">
              <el-table
                v-loading="secLoading"
                :data="props.row.children"
                :show-header="false"
                row-key="id"
                @row-click="rowClickSec"
              >
                <el-table-column width="55" align="center">
                  <div class="line"></div>
                </el-table-column>
                <template v-for="(item, index) in column">
                  <el-table-column
                    align="center"
                    :key="item.prop || index"
                    :prop="item.prop"
                    :width="item.width"
                    v-if="item.sub !== false"
                    :label="item.label"
                  >
                    <template slot-scope="scope">
                      <p v-if="item.prop === 'ddbh'" class="color6">
                        {{ scope.row[item.prop] }}
                      </p>
                      <template v-else>{{ scope.row[item.prop] }}</template>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column
            v-for="(item, index) in column"
            :key="item.prop || index"
            :prop="item.prop"
            :min-width="item.width"
            :label="item.label"
            align="center"
            :fixed="item.fixed"
            :class-name="item.click ? 'mouse-hover' : ''"
          >
            <template slot-scope="scope">
              <el-tag
                v-if="item.prop === 'status'"
                size="mini"
                class="table-tag"
                :type="scope.row.type"
                >{{ scope.row.status }}</el-tag
              >
              <template v-else
                >{{ scope.row[item.prop]
                }}<span
                  class="expand-info"
                  v-if="item.prop === 'ddbh' && scope.row.merge == 'true'"
                  >合</span
                ></template
              >
            </template>
          </el-table-column>

          <el-table-column
            header-align="center"
            width="200"
            align="center"
            fixed="right"
          >
            <template slot="header" slot-scope="scope">操作</template>
            <template slot-scope="scope">
              <div class="bp">
                <el-button
                  type="text"
                  icon="el-icon-edit-outline"
                  @click="editRow(scope.row, scope.column, true)"
                  size="mini"
                  >{{
                    scope.row.merge === 'false' ? '编辑' : '详情'
                  }}</el-button
                >
              </div>
              <el-button
                slot="reference"
                type="text"
                v-if="scope.row.status === '待下达'"
                icon="el-icon-delete"
                class="danger"
                size="mini"
                @click.stop="delOrder(scope.row.ddbh)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            @current-change="currentChange"
            @size-change="sizeChange"
            :current-page.sync="page.current"
            :page-size.sync="page.size"
            layout="sizes, prev, pager, next"
            :total="page.total"
          />
        </div>
      </div>
    </div>
    <merge
      :mergeIds="mergeIds"
      :dialogVisible="mergeVisible"
      @close="mergeShow"
    />
    <import-order :dialogVisible="importVisible" @close="importShow" />
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form label-width="80px" :inline="true">
        <el-form-item label="订单编号">
          <el-input v-model="u_params.ddbh"></el-input>
        </el-form-item>
        <el-form-item label="订单类型">
          <el-select v-model="u_params.ddlx" placeholder="请选择组织">
            <el-option
              v-for="item in orderTypeOption"
              :key="item.id"
              :label="item['key_value']"
              :value="item['key_value']"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <el-form label-width="80px" :inline="true">
        <el-form-item label="组织">
          <el-select v-model="u_params.org" placeholder="请选择组织">
            <el-option
              v-for="item in orgOption"
              :key="item.id"
              :label="item['key_value']"
              :value="item['key_value']"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="品种">
          <el-select v-model="u_params.pz" placeholder="请选择品种">
            <el-option
              v-for="item in pzOption"
              :key="item.id"
              :label="item['key_value']"
              :value="item['key_value']"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <el-form label-width="80px" :inline="true">
        <el-form-item label="支别">
          <el-select v-model="u_params.zb" placeholder="请选择支别">
            <el-option
              v-for="item in branchOption"
              :key="item.id"
              :label="item['key_value']"
              :value="item['key_value']"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="重量">
          <el-input v-model="u_params.zl"></el-input>
        </el-form-item>
      </el-form>
      <el-form label-width="80px" :inline="true">
        <el-form-item label="订单交期">
          <el-date-picker
            v-model="u_params.ddjq"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="isOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import merge from './basiclier/merge';
import importOrder from './basiclier/import';
import {
  getOrder,
  getSecOrder,
  delOrder,
  updateOrder,
  addOrder,
} from '@/api/order';
export default {
  data() {
    return {
      dialogTitle: '',
      dialogVisible: false,
      tableHeight: 0,
      u_params: {},
      search: {
        org: '',
        cj: '',
        pz: '',
        ddjq: '',
      },
      secLoading: false,
      mergeVisible: false,
      mergeIds: [],
      importVisible: false,
      page: {
        total: 56,
        size: 10,
        current: 1,
      },
      data: [],
      column: [
        {
          prop: 'ddbh',
          label: '订单编号',
          width: '200',
          fixed: 'left',
          click: true,
        },
        { prop: 'ddlx', label: '订单类型', width: '100' },
        { prop: 'org', label: '组织', width: '100' },
        { prop: 'pz', label: '品种名称', width: '150' },
        { prop: 'zb', label: '支别', width: '100' },
        { prop: 'zl', label: '重量(吨)', width: '100' },
        { prop: 'ddjq', label: '订单交期', width: '200' },
        { prop: 'update_time', label: '更新时间', width: '200' },
        { prop: 'status', label: '订单状态', width: '100', sub: false },
      ],
    };
  },
  components: {
    merge,
    importOrder,
  },
  created() {
    this.getOrder();
  },
  mounted() {
    this.$nextTick(() => {
      this.getHeight();
    });
  },
  computed: {
    orderTypeOption() {
      return this.$store.getters.orderTypeOption;
    },
    branchOption() {
      return this.$store.getters.branchOption;
    },
    orgOption() {
      return this.$store.getters.orgOption;
    },
    cjOption() {
      return this.$store.getters.cjOption;
    },
    pzOption() {
      return this.$store.getters.pzOption;
    },
  },
  methods: {
    insertOrder() {
      this.dialogTitle = '新增订单';
      this.dialogVisible = true;
      this.u_params = {};
    },
    async isOk() {
      let res;
      if (this.dialogTitle == '新增订单') {
        res = await addOrder(this.u_params);
      } else if (this.dialogTitle == '更新订单') {
        res = await updateOrder(this.u_params);
      }
      if (res.code == 1) {
        this.$message({
          message: '操作成功',
          type: 'success',
        });
        this.dialogVisible = false;
        this.getOrder();
      }
    },
    getHeight() {
      this.tableHeight = this.$refs.table.offsetHeight;
    },
    async getOrder() {
      let form = Object.assign({}, this.search);
      form.page = this.page.current - 1;
      form.size = this.page.size;
      for (let i in form) {
        if (form[i] === '') {
          delete form[i];
        }
      }
      this.loading = true;
      const res = await getOrder(form);
      if (res.code == 1 && res.data) {
        this.$nextTick(() => {
          this.loading = false;
        });
        // 初始children字段 防止第一次点击展开时无字段导致表格不更新
        res.data.dataList.map((item) => {
          item.children = [];
          item.type =
            item.status == '已下达'
              ? 'success'
              : item.status == '待下达'
              ? 'warning'
              : 'error';
        });
        this.data = res.data.dataList;
        this.page.total = res.data.total;
      } else {
        this.loading = false;
        this.data = [];
        this.page.total = 0;
      }
    },
    // 展开二级订单
    async expandRow(row, expand) {
      if (expand) {
        this.secLoading = true;
        let id = row.ddbh;
        const res = await getSecOrder({ oriddbh: id, page: 0, size: -1 });
        if (res.code == 1) {
          row.children = res.data.dataList;
        }
        this.secLoading = false;
      } else {
        row.children = [];
      }
    },
    delOrder(id, type) {
      let ids = [];
      if (type == 'multiple') {
        let selection = this.$refs.orderTable.selection;
        if (selection.length > 0) {
          selection.map((item) => {
            ids.push(item.ddbh);
          });
        } else {
          this.$message({
            message: '请选择需要删除的订单',
            iconClass: 'el-icon-warning',
            customClass: 'common-message',
          });
          return;
        }
      } else {
        ids = [id];
      }
      this.$confirm('是否确认删除该订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        const res = await delOrder({ ddbhs: ids });
        if (res.code == 1) {
          this.$message({
            message: '删除成功',
            iconClass: 'el-icon-success',
            customClass: 'common-message',
          });
          this.getOrder();
        }
      });
    },
    editRow(row, column) {
      if (row.merge === 'true') {
        let { ddbh } = row;
        let path = 'detail';
        this.$router.push({
          path: `/basiclier/${path}`,
          query: { ddbh: ddbh },
        });
      } else {
        this.dialogTitle = '更新订单';
        this.dialogVisible = true;
        this.u_params = row;
      }
    },
    rowClickSec(row, column, event) {
      let { ddbh } = row;
      let { oriddbh } = row;
      this.$router.push({
        path: '/basiclier/detailSec',
        query: { ddbh, oriddbh },
      });
    },
    mergeShow(type) {
      if (type == 'open') {
        let selection = this.$refs.orderTable.selection;
        if (selection.length > 1) {
          let ids = [];
          selection.map((item) => {
            ids.push(item.ddbh);
          });
          this.mergeIds = ids;
          this.mergeVisible = true;
        } else {
          this.$message({
            message: '请选择需要合并的订单',
            iconClass: 'el-icon-warning',
            customClass: 'common-message',
          });
        }
      } else {
        if (type == 'update') {
          this.getOrder();
        }
        this.mergeVisible = false;
      }
    },
    importShow() {
      this.importVisible = !this.importVisible;
    },
    getRowClass({ row }) {
      if (row.merge == 'false') {
        //判断当前行是否有子数据或者根据实际情况设置
        return 'row-expand-cover';
      } else {
        return 'table-expand';
      }
    },
    currentChange(current) {
      this.page.current = current;
      this.getOrder();
    },
    sizeChange(size) {
      this.page.size = size;
      this.page.current = 1;
      this.getOrder();
    },
    selectionChange(selected) {
      console.log(selected);
    },
  },
};
</script>

<style lang="scss">
@import '~@/assets/css/order.scss';
.box-main {
  height: calc(100% - 100px);
  margin: 10px 10px;
  box-sizing: border-box;
}
.mouse-hover {
  cursor: pointer;
}
</style>
